from supabase import create_async_client, AsyncClient
from typing import List, Optional
import datetime

class AccountsAPI:
    def __init__(self, client: AsyncClient):
        self.client = client
        self.table_name = "accounts"

    async def create_account_by_users(
        self,
        email: str,
        phone: Optional[str],
        nick_name: Optional[str],
        tenant_id: Optional[str],
        avatar: Optional[str],
        user_id: str,  # supabase.auth.user id
    ):
        now = datetime.datetime.utcnow().isoformat()
        record = {
            "id": user_id,
            "created_at": now,
            "email": email,
            "phone": phone,
            "nick_name": nick_name,
            "tenant_id": tenant_id,
            "avatar": avatar,
        }
        response = await self.client.table(self.table_name).insert(record).execute()
        return response.data

    async def get_account(self, user_id: str) -> Optional[dict]:
        response = await self.client.table(self.table_name).select("*").eq("id", user_id).single().execute()
        return response.data

    async def update_account(self, user_id: str, updates: dict) -> Optional[dict]:
        response = await self.client.table(self.table_name).update(updates).eq("id", user_id).execute()
        return response.data

    async def delete_account(self, user_id: str) -> None:
        await self.client.table(self.table_name).delete().eq("id", user_id).execute()
